package net.mihome.app.ui.view;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.easemob.chat.EMContactManager;
import com.easemob.chatuidemo.Constant;
import com.easemob.chatuidemo.activity.AddContactActivity;
import com.easemob.chatuidemo.activity.ChatActivity;
import com.easemob.chatuidemo.activity.GroupsActivity;
import com.easemob.chatuidemo.activity.NewFriendsMsgActivity;
import com.easemob.chatuidemo.widget.Sidebar;

import net.mihome.app.AppContext;
import net.mihome.app.R;
import net.mihome.app.adapter.MiHomeContactAdapter;
import net.mihome.app.bean.User;
import net.mihome.app.common.UIHelper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


/**
 * Created by ZHAO on 2014/12/21 0021.
 */
public class MiHomeContractView  extends ListView {

    private MiHomeContactAdapter adapter;
    private List<User> contactList;
    private boolean hidden;
    private Sidebar sidebar;
    private List<String> blackList;
    private List<String> contractList=new ArrayList<>();
    public MiHomeContractView(Context context) {
        super(context);
        afterInit();
    }

    public MiHomeContractView(Context context, AttributeSet attrs) {
        super(context, attrs);
        afterInit();
    }

    public MiHomeContractView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        afterInit();
    }
    public void afterInit(){
        //黑名单列表
        setDescendantFocusability(ListView.FOCUS_AFTER_DESCENDANTS);
        blackList = EMContactManager.getInstance().getBlackListUsernames();
        contactList = new ArrayList<User>();
        getContactList();
        // 设置adapter
        adapter = new MiHomeContactAdapter(getContext(), R.layout.row_contact, contactList, sidebar);
        this.setAdapter(adapter);
        this.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String username = adapter.getItem(position).getUsername();
                if (Constant.NEW_FRIENDS_USERNAME.equals(username)) {
                    // 进入申请与通知页面
                    User user = AppContext.getInstance().getContactList().get(Constant.NEW_FRIENDS_USERNAME);
                    user.setUnreadMsgCount(0);
                    getContext().startActivity(new Intent(getContext(), NewFriendsMsgActivity.class));
                } else if (Constant.GROUP_USERNAME.equals(username)) {
                    // 进入圈子列表页面
                    getContext().startActivity(new Intent(getContext(), GroupsActivity.class));
                }
                else if (Constant.ADD_CONTRACT.equals(username)) {
                    // 进入添加好友页面
                    getContext().startActivity(new Intent(getContext(), AddContactActivity.class));
                }
                else {
                    // demo中直接进入聊天页面，实际一般是进入用户详情页
                    getContext().startActivity(new Intent(getContext(), ChatActivity.class).putExtra("userId", adapter.getItem(position).getUsername()));
                }
            }
        });
    }

    public void initData(){
        new AsyncTask<String, Integer, String>() {
            @Override
            protected String doInBackground(String... strings) {
                getContactList();
                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                adapter.notifyDataSetChanged();
                super.onPostExecute(s);
            }
        }.execute();
    }


    /**
     * 获取联系人列表，并过滤掉黑名单和排序
     */
    private void getContactList() {
        contactList.clear();
        //获取本地好友列表
        Map<String, User> users = AppContext.getInstance().getContactList();
        if(users==null){
            UIHelper.showAlertDialog(getContext(),"提示","无法获取联系人信息，请重新登录.",new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    UIHelper.loginOrLogout((Activity)getContext());
                }
            });
        }
        Iterator<Map.Entry<String, User>> iterator = users.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, User> entry = iterator.next();
            if (!entry.getKey().equals(Constant.NEW_FRIENDS_USERNAME) && !entry.getKey().equals(Constant.GROUP_USERNAME)
                    && !blackList.contains(entry.getKey()))
                contactList.add(entry.getValue());
        }
        // 排序
        Collections.sort(contactList, new Comparator<User>() {

            @Override
            public int compare(User lhs, User rhs) {
                return lhs.getUsername().compareTo(rhs.getUsername());
            }
        });

        // 加入"申请与通知"和"圈子"
        contactList.add(0, users.get(Constant.GROUP_USERNAME));
        // 把"申请与通知"添加到首位
        contactList.add(0, users.get(Constant.NEW_FRIENDS_USERNAME));
    }

}
